//
//  SQVoiceView.m
//  energy
//
//  Created by 周曼迪 on 2021/7/23.
//

#import "SQVoiceView.h"
#define kFakeTimerDuration       0.2
#define kMaxRecordDuration       60     //最长录音时长
#define kRemainCountingDuration  10     //剩余多少秒开始倒计时

@implementation SQVoiceView

- (instancetype)init{
    self = [super initWithFrame:CGRectMake(0, 0, W(360), W(35))];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self buildView];
    }
    return self;
}

-(void)buildView{
    UIView *voice_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, W(250), W(35))];
    [voice_view SQCornerRadius:7];
    voice_view.backgroundColor = [UIColor colorWithHexString:@"#F6F6F6"];
    [self addSubview:voice_view];
    // yuyin_icon
    UIImage *yuyin_icon = [UIImage imageNamed:@"voice"];
    UIImageView *yuyin_icon_imgview = [[UIImageView alloc] initWithImage:yuyin_icon];
    yuyin_icon_imgview.frame = CGRectMake(12.5, 5, 25, 25);
    [voice_view addSubview:yuyin_icon_imgview];
    
    CGFloat sub_width = voice_view.width-55;
    CGFloat item_with = sub_width/30.f;
    for (int i = 0; i < 30; i++) {
        CGFloat height = 0;
        if (i<15) {
            height = 10+i;
        }else{
            height = 25-i;
        }
        UIView *item_veiw = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(yuyin_icon_imgview.frame)+5+i*item_with, (voice_view.height-height)/2.f, item_with-2, height)];
        item_veiw.backgroundColor = [UIColor colorNamed:@"notColor"];
        [item_veiw SQCornerRadius:(item_with-2)/2.f];
        [voice_view addSubview:item_veiw];
    }
    // 播放语音按钮
    UIButton *play_record_btn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(yuyin_icon_imgview.frame)+5, 0, voice_view.width-(CGRectGetMaxX(yuyin_icon_imgview.frame)+5)-30, voice_view.height)];
    play_record_btn.userInteractionEnabled = NO;
    play_record_btn.backgroundColor = [UIColor clearColor];
    play_record_btn.alpha = 0.5;
    [play_record_btn addTarget:self action:@selector(play_record_btn_action:) forControlEvents:UIControlEventTouchUpInside];
    [voice_view addSubview:play_record_btn];
    self.play_record_btn = play_record_btn;
    
    // 删除录音按钮
    UIButton *close_btn = [[UIButton alloc] initWithFrame:CGRectMake(voice_view.width-30, 0, W(15), W(15))];
    close_btn.hidden = YES;
    [close_btn setImage:[UIImage imageNamed:@"del"] forState:UIControlStateNormal];
    [voice_view addSubview:close_btn];
    [close_btn addTarget:self action:@selector(close_btn_del_action) forControlEvents:UIControlEventTouchUpInside];
    self.close_btn = close_btn;
    
    UIButton *start_voice_btn = [[UIButton alloc] initWithFrame:CGRectMake(W(270), W(0), W(85), W(35))];
    start_voice_btn.enabled = NO;//将事件往上传递
    [start_voice_btn setTitle:@"开始录音" forState:UIControlStateNormal];
    [start_voice_btn setTitleColor:[UIColor colorNamed:@"notColor"] forState:UIControlStateNormal];
    start_voice_btn.titleLabel.font = [UIFont systemFontOfSize:16];
    start_voice_btn.backgroundColor =[UIColor colorWithHexString:@"#6BA2FF"];
    [start_voice_btn SQCornerRadius: 35/2.f];
    [self addSubview:start_voice_btn];
    self.start_voice_btn = start_voice_btn;
}
    
- (void)buildPlayVoiceVie:(NSString *)urlStr{
    
    if (![urlStr isEqualToString:@""]) {
        self.hdr_audio = urlStr;
        self.play_record_btn.selected = YES;
        [self refreshYuyinView];
    }

   
}


// 播放录音
- (void)play_record_btn_action:(UIButton *)sender{
    NSString *hdr_audio = [NSString stringWithFormat:@"%@%@",LC_ImageHeader,self.hdr_audio];
    
    if (![hdr_audio CheckNillWithString]) {
        [self refreshYuyinView];
        if (sender.selected == YES) {
            [[NewPlayerManager manager] playNetMusic:[NSString stringWithFormat:@"%@%@",LC_ImageHeader,self.hdr_audio]];
            
            [[NewPlayerManager manager] playerPause];
        }else{
            //0:caf 1:amr 2:mp3
            if ([self.hdr_audio containsString:@".mp3"]) {
                [ShlRecordManager manager].record_type = 2;
            }
            if ([self.hdr_audio containsString:@".caf"]) {
                [ShlRecordManager manager].record_type = 0;
            }
            if ([self.hdr_audio containsString:@".amr"]) {
                [ShlRecordManager manager].record_type = 1;
            }
            [[ShlRecordManager manager] playRecord];
        }
    }

    
   
    
}

// 删除语音按钮点击
- (void)close_btn_del_action{
    self.close_btn.hidden = YES;
    self.play_record_btn.userInteractionEnabled = NO;
    [self deleteVoiceData];
}

// 刷新语音view
- (void)refreshYuyinView{
    if (self.hdr_audio&&![self.hdr_audio CheckNillWithString]) {
        self.close_btn.hidden = NO;
        self.play_record_btn.userInteractionEnabled = YES;
    }else{
        self.close_btn.hidden = YES;
        self.play_record_btn.userInteractionEnabled = NO;
    }
}
#pragma mark - UI部分
- (void)startFakeTimer
{
    if (_fakeTimer) {
        [_fakeTimer invalidate];
        _fakeTimer = nil;
    }
    self.fakeTimer = [NSTimer scheduledTimerWithTimeInterval:kFakeTimerDuration target:self selector:@selector(onFakeTimerTimeOut) userInfo:nil repeats:YES];
    [_fakeTimer fire];
}

- (void)stopFakeTimer
{
    if (_fakeTimer) {
        [_fakeTimer invalidate];
        _fakeTimer = nil;
    }
}

- (void)onFakeTimerTimeOut
{
    self.duration += kFakeTimerDuration;
    NSLog(@"+++duration+++ %f",self.duration);
    float remainTime = kMaxRecordDuration-self.duration;
    if ((int)remainTime == 0) {
        self.currentRecordState = BBVoiceRecordState_Normal;
        [self dispatchVoiceState];
    }
    else if ([self shouldShowCounting]) {
        self.currentRecordState = BBVoiceRecordState_RecordCounting;
        [self dispatchVoiceState];
        [self.voiceRecordCtrl showRecordCounting:remainTime];
    }
    else
    {
        float fakePower = (float)(1+arc4random()%99)/100;
        [self.voiceRecordCtrl updatePower:fakePower];
    }
}

- (BOOL)shouldShowCounting
{
    if (self.duration >= (kMaxRecordDuration-kRemainCountingDuration) && self.duration < kMaxRecordDuration && self.currentRecordState != BBVoiceRecordState_ReleaseToCancel) {
        return YES;
    }
    return NO;
}

- (void)resetState
{
    [self stopFakeTimer];
    self.duration = 0;
    self.canceled = YES;
}
// 点击开始
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [self endEditing:YES];
    NSLog(@"点击开始");
    CGPoint touchPoint = [[touches anyObject] locationInView:self];
    if (CGRectContainsPoint(self.start_voice_btn.frame, touchPoint)) {
        if (![[ShlRecordManager manager] RequestPermission]) {
            return;
        }
        self.is_touched = YES;
        self.currentRecordState = BBVoiceRecordState_Recording;
        [self dispatchVoiceState];
        // 开始录音mp3 格式
        [[ShlRecordManager manager] initFilePathWithType:2];
        [[ShlRecordManager manager] startRecord];
    }
}
// 监听移动
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.is_touched == NO) {
        return;
    }
    NSLog(@"监听移动");
    if (_canceled) {
        return;
    }
    if (![[ShlRecordManager manager] RequestPermission]) {
        return;
    }
    CGPoint touchPoint = [[touches anyObject] locationInView:self];
    if (CGRectContainsPoint(self.start_voice_btn.frame, touchPoint)) {
        _canceled = NO;
        self.currentRecordState = BBVoiceRecordState_Recording;
    }
    else
    {
        _canceled = YES;
        self.currentRecordState = BBVoiceRecordState_ReleaseToCancel;
    }
    [self dispatchVoiceState];
}
// 录音点击结束
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.is_touched == NO) {
        return;
    }
    NSLog(@"录音结束");
    self.is_touched = NO;
    if (![[ShlRecordManager manager] RequestPermission]) {
        return;
    }
    if (_canceled) {
        [[ShlRecordManager manager] stopRecord];
        // 删除所有录音文件
        [[ShlRecordManager manager] deleteAllFile];
        self.currentRecordState = BBVoiceRecordState_Normal;
        [self dispatchVoiceState];
        return;
    }
    
    CGPoint touchPoint = [[touches anyObject] locationInView:self];
    if (CGRectContainsPoint(self.start_voice_btn.frame, touchPoint)) {
        if (self.duration < 0.5) {
            // 删除所有录音文件
            [[ShlRecordManager manager] stopRecord];
            [[ShlRecordManager manager] deleteAllFile];
            self.hdr_audio = @"";
            // 刷新语音view
            [self refreshYuyinView];
            [self.voiceRecordCtrl showToast:@"时间太短了"];
        }
        else
        {
            
            //upload voice
            // 获取音频文件转base64，上传
            self.hdr_audio = [[ShlRecordManager manager] stopMp3Record];
            self.voiceViewBlock(self.hdr_audio);
//            [self.voiceRecordCtrl showToast:@"录音完成"];
            [CCToast showMessage:@"录音完成"];
            // 刷新语音view
            [self refreshYuyinView];
        }
    }
    self.currentRecordState = BBVoiceRecordState_Normal;
    [self dispatchVoiceState];
}

- (void)deleteVoiceData{
    // 删除所有录音文件
    [[ShlRecordManager manager] stopRecord];
    [[ShlRecordManager manager] deleteAllFile];
    self.hdr_audio = @"";
    // 刷新语音view
    [self refreshYuyinView];
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"录音取消");
    [[ShlRecordManager manager] stopRecord];
    // 删除所有录音文件
    [[ShlRecordManager manager] deleteAllFile];
    if (_canceled) {
        return;
    }
    if (![[ShlRecordManager manager] RequestPermission]) {
        return;
    }
    CGPoint touchPoint = [[touches anyObject] locationInView:self];
    if (CGRectContainsPoint(self.start_voice_btn.frame, touchPoint)) {
        if (self.duration < 0.5) {
            [self.voiceRecordCtrl showToast:@"太短了"];
        }
        else
        {
            //upload voice
        }
    }
    self.currentRecordState = BBVoiceRecordState_Normal;
    [self dispatchVoiceState];
}

- (void)dispatchVoiceState
{
    if (_currentRecordState == BBVoiceRecordState_Recording) {
        self.canceled = NO;
        [self startFakeTimer];
    }
    else if (_currentRecordState == BBVoiceRecordState_Normal)
    {
        [self resetState];
    }
    //[_btnRecord updateRecordButtonStyle:_currentRecordState];
    [self.voiceRecordCtrl updateUIWithRecordState:_currentRecordState];
}

- (BBVoiceRecordController *)voiceRecordCtrl
{
    if (_voiceRecordCtrl == nil) {
        _voiceRecordCtrl = [BBVoiceRecordController new];
    }
    return _voiceRecordCtrl;
}

-(void)showWithChooseBlock:(SQVoiceViewBlock)voiceViewBlock{
    self.voiceViewBlock = voiceViewBlock;
}
@end
